import { Injectable, NestMiddleware } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { isStr, isEmpty } from "st-common-core";
import { decryptAnyByTripleDes, DesTripleHeaderNameConst } from "st-common-encrypt";
import { EnvNameEnum } from "../../env";
import { getReqDataFromReq, setReqData } from "../../req";

/**
 * 对请求数据进行解密的全局中间件
 */
@Injectable()
export class ReqDataDecryptMiddleware implements NestMiddleware {

  constructor(private readonly configService: ConfigService) {
  }

  use(req: any, res: any, next: () => void) {
    // 如果在环境变量中配置关闭了请求数据的加密
    if (!this.configService.get<boolean>(EnvNameEnum.REQ_DATA_IS_ENCRYPT)) return next();
    // 获取请求头对象
    const reqHeaders = req.headers;
    // 如果在请求头中标记此次请求数据没有加密
    if (reqHeaders[DesTripleHeaderNameConst.IS_DES_TRIPLE] !== 'true') return next();
    // 获取请求头中用于加密请求数据的密钥
    const key = reqHeaders[DesTripleHeaderNameConst.KEY];
    // 如果密钥存在且不为空，则对请求数据进行解密
    if (isStr(key) && !isEmpty(key)) {
      // 获取请求数据
      const reqData = getReqDataFromReq(req);
      // 解密请求数据
      setReqData(req, decryptAnyByTripleDes({
        secretData: reqData,
        key
      }));
    }
    next();
  }
}
